//
//  PictureBrowserCell.swift
//  JLWeibo
//
//  Created by sunjinliang on 15/12/18.
//  Copyright © 2015年 sunjinliang. All rights reserved.
//

import UIKit
import SDWebImage
import SVProgressHUD
protocol PictureBrowserCellClickImageOutDelegate :NSObjectProtocol{
    func PictureBrowserCellClickImageOut()
    func PictureBrowserCellDidZoom(scale: CGFloat)
}
class PictureBrowserCell: UICollectionViewCell,UIScrollViewDelegate {
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    weak var CellClickImageDelegate : PictureBrowserCellClickImageOutDelegate?
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    var imgView = UIImageView()
    private lazy var placeHolder: ProgressImageView = ProgressImageView()
    var scrollView = UIScrollView()
    var imageURL : NSURL? {
        didSet{
            resetContentCell()
            guard  let placeHolderImage = SDWebImageManager.sharedManager().imageCache.imageFromDiskCacheForKey(imageURL?.absoluteString) else{
                return
            }
            setPlaceHolderImage(placeHolderImage)
            let newURL = replacebmiddle()
            imgView.sd_setImageWithURL(newURL, placeholderImage: placeHolderImage, options: [SDWebImageOptions.RetryFailed, SDWebImageOptions.RefreshCached], progress: { (current, total) -> Void in
                    dispatch_async(dispatch_get_main_queue(), { () -> Void in
                        self.placeHolder.progress = CGFloat(current) / CGFloat(total)
                    })
                }) { (image, error, _, _) -> Void in
                    if image == nil{
                        SVProgressHUD.showErrorWithStatus("您的网络不给力")
                        return
                    }
                    self.placeHolder.hidden = true
                     self.setPoint(image)
            }
        }
    }
    //点击图片退出
    @objc func tapImagView(){
        CellClickImageDelegate?.PictureBrowserCellClickImageOut()
        
    }
    func setPlaceHolderImage(image : UIImage){
        placeHolder.hidden = false
        placeHolder.image = image
        placeHolder.sizeToFit()
        placeHolder.center = scrollView.center
    }
    func replacebmiddle()->NSURL{
        var urlString = imageURL?.absoluteString
        urlString =  urlString?.stringByReplacingOccurrencesOfString("/thumbnail/", withString: "/bmiddle/")
        return NSURL(string: urlString!)!
    }
    func setupUI(){
        addSubview(scrollView)
        scrollView.addSubview(imgView)
        scrollView.addSubview(placeHolder)
        var rect = bounds
        rect.size.width -= 20
        scrollView.frame = rect
        scrollView.delegate = self
        scrollView.minimumZoomScale = 0.5
        scrollView.maximumZoomScale = 2
        scrollView.showsVerticalScrollIndicator = false
        let tapImage = UITapGestureRecognizer(target: self, action: "tapImagView")
        imgView.addGestureRecognizer(tapImage)
        imgView.userInteractionEnabled = true
    }
    func resetContentCell(){
        imgView.transform = CGAffineTransformIdentity
        scrollView.contentSize = CGSizeZero
        scrollView.contentInset = UIEdgeInsetsZero
        scrollView.contentOffset = CGPointZero
        
    }
    func setPoint(image: UIImage){
        let size = self.displaySize(image)
        if size.height < scrollView.bounds.height{
            imgView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            let y = (scrollView.bounds.height - size.height) * 0.5
            scrollView.contentInset = UIEdgeInsets(top: y, left: 0, bottom: 0, right: 0)
            //imgView.center = scrollView.center
        }else{
            imgView.frame = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            scrollView.contentSize = size
        }
        
        
    }
func displaySize(image: UIImage)->CGSize{
    let w = scrollView.bounds.size.width
    let height = image.size.height * w / image.size.width
    return CGSize(width: w, height: height)
}
}
extension PictureBrowserCell {
    
    func viewForZoomingInScrollView(scrollView: UIScrollView) -> UIView? {
        return imgView
    }
    
    func scrollViewDidEndZooming(scrollView: UIScrollView, withView view: UIView?, atScale scale: CGFloat) {
        if scale < 0.8 {
            CellClickImageDelegate?.PictureBrowserCellClickImageOut()
            return
        }
        var offSetY = (scrollView.bounds.size.height - (view?.frame.size.height)!) * 0.5
        offSetY = offSetY > 0 ? offSetY : 0
        var offSetX = (scrollView.bounds.size.width - (view?.frame.size.width)!) * 0.5
        offSetX = offSetX > 0 ? offSetX : 0
        
        scrollView.contentInset = UIEdgeInsets(top: offSetY, left: offSetX, bottom: 0, right: 0)
        
    }
    func scrollViewDidZoom(scrollView: UIScrollView) {
        CellClickImageDelegate?.PictureBrowserCellDidZoom(imgView.transform.a)
    }
}